package com.wx.tgp.netty.demo.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.apache.log4j.Logger;

/**
 * netty的第一个实例demo
 */
public class HelloServer {

    private Logger log = Logger.getLogger(HelloServer.class);

    public void bind(int port) throws Exception{
        // 服务器线程组，用于网络事件的处理，一个用于接收客户端的连接
        // 另一个处理socketChannel的网络读写
        EventLoopGroup boosGroup = new NioEventLoopGroup();
        EventLoopGroup writerGroup = new NioEventLoopGroup();

        try{
            // NIO服务器的启动类，降低开发难度
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(boosGroup,writerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,1024)
                    .childHandler(new ChildChannelHandler());
            ChannelFuture f = bootstrap.bind(port).sync();
            log.info("TimeServer启动成功");
            f.channel().closeFuture().sync();
        }catch (Exception e){
            log.info("完了");
            e.printStackTrace();
        } finally {
            // 释放资源
            boosGroup.shutdownGracefully();
            writerGroup.shutdownGracefully();
            log.info("服务器释放了资源");
        }
    }


    public static void main(String args[]) throws Exception{
        HelloServer server =new HelloServer();
        server.bind(8000);
    }
}
